/*
 * @Author: WangLi
 * @Date: 2021-07-23 13:49:12
 * @LastEditors: WangLi
 * @LastEditTime: 2024-03-14 13:32:13
 * @Description:
 */
import { canIUseModel } from "../../../utils/version";
const path = "../radio-group/index";
Component({
  behaviors: ["wx://form-field"],
  externalClasses: ["custom-class", "label-class", "icon-class"],
  options: {
    multipleSlots: true,
    addGlobalClass: true,
  },
  relations: {
    [path]: {
      type: "ancestor",
      linked() {
        this.updateFromParent();
      },
      linkChanged() {
        this.updateFromParent();
      },
      unlinked() {
        this.updateFromParent();
      },
    },
  },
  properties: {
    name: null,
    value: null,
    disabled: Boolean,
    useIconSlot: Boolean,
    checkedColor: String,
    labelPosition: {
      type: String,
      value: "right",
    },
    labelDisabled: Boolean,
    iconSize: {
      type: null,
      value: 60,
    },
  },
  data: {
    direction: "",
    parentDisabled: false,
    last: false,
  },
  created() {
    Object.defineProperty(this, "parent", {
      get: () => this.getRelationNodes(path)[0],
    });

    Object.defineProperty(this, "index", {
      get: () => this.parent?.children?.indexOf(this),
    });
  },
  ready() {
    this.setData({
      last: this.parent?.children.length === this.index + 1,
    });
  },
  methods: {
    updateFromParent() {
      if (!this.parent) {
        return;
      }

      const { value, disabled: parentDisabled, direction } = this.parent.data;

      this.setData({
        value,
        direction,
        parentDisabled,
      });
    },

    emitChange(value) {
      const instance = this.parent || this;
      instance.triggerEvent("input", value);
      instance.triggerEvent("change", value);

      if (canIUseModel()) {
        instance.setData({ value });
      }
    },

    onChange() {
      if (!this.data.disabled && !this.data.parentDisabled) {
        this.emitChange(this.data.name);
      }
    },

    onClickLabel() {
      const { disabled, parentDisabled, labelDisabled, name } = this.data;
      if (!(disabled || parentDisabled) && !labelDisabled) {
        this.emitChange(name);
      }
    },
  },
});
